<?php
/**
 * CPDF library
 *
 * This library extends the FPDF library, allowing
 * the creation of custom header and footers, as well
 * as containing all general formatting options.
 * @package Packages
 */

/**
 *
 */
require_once(AD_SERVER_PATH . '/external/fpdf/fpdf.php');
require_once(AD_SERVER_PATH . '/pkgs/utils.php');

/**
 * CPDF library
 *
 * This library extends the FPDF library, allowing
 * the creation of custom header and footers, as well
 * as containing all general formatting options.
 * @package Packages
 */
class CPDF extends FPDF
{
	private $left_header_text;
	private $right_header_text;

	/**
	 * Constructor
	 *
	 * Calls FPDF constructor, passing new default values,
	 * and also sets general formatting options.
	 * @param char $orientation
	 * @param string $unit
	 * @param array
	 */
	public function __construct($orientation = 'P', $unit = 'mm', $format = array(216, 279)) //8.5x11 in
	{
		parent::__construct($orientation, $unit, $format);

		$this->AliasNbPages();
		$this->SetFillColor(200, 200, 200);
		$this->SetFont('Arial', '', 7);
		$this->SetMargins(20, 20, 20);
	}

	/**
	 * Set left header value
	 *
	 * Sets value displayed on left side of header.
	 * @param string $string
	 */
	public function set_left_header_text($string)
	{
		$this->left_header_text = $string;
	}

	/**
	 * Set right header value
	 *
	 * Sets value displayed on right side of header.
	 * @param string $string
	 */
	public function set_right_header_text($string)
	{
		$this->right_header_text = $string;
	}

	/**
	 * Print header
	 *
	 * Overwrites FPDFs Header method to create custom header.
	 */
	public function Header()
	{
		$this->SetY(10);
		$this->SetX(10);
		$this->SetFont('Arial', '', 9);
		$this->Cell(146, 5, $this->left_header_text, 'B');
		$this->Cell(50, 5, $this->right_header_text, 'B', 0, 'R');
		$this->Ln(20);
	}

	/**
	 * Print footer
	 *
	 * Overwrites FPDFs Footer method to create custom footer.
	 */
	public function Footer()
	{
		$this->SetY(-15);
		$this->SetX(10);
		$this->SetFont('Arial', '', 9);
		$this->Cell(146, 5, ('Page ' . $this->PageNo() . ' of {nb}'), 'T');
		$this->Cell(50, 5, date('m/d/Y h:i A'), 'T', 0, 'R');
	}

	/**
	 * Print image
	 *
	 * Overloads FPDFs Image method, allowing image to
	 * come from the local server. This is needed to
	 * work around the fact that FPDF incorrectly
	 * parses image URLs that have a query string.
	 * @param string $file
	 * @param int $x
	 * @param int $y
	 * @param int $w
	 * @param int $h
	 * @param string $type
	 * @param string $link
	 * @param int $ml_number
	 * @param int $index
	 */
	public function Image($file, $x = null, $y = null, $w = 0, $h = 0, $type = '', $link = '', $ml_number = 0, $index = 0)
	{
		if (0 < $ml_number)
		{
			$file = CUtils::mk_tmp_img($ml_number, $index);
			$file = $file[0];
		}

		parent::Image($file, $x, $y, $w, $h, $type, $link);

		if (0 < $ml_number)
		{
			unlink($file);
		}
	}
}
